//
//  MHSliderView.swift
//  Kool Car
//
//  Created by huangweiqiang on 2022/2/8.
//

import UIKit

typealias MHSliderViewBlock = (Double, Double)->()
//最小高度为38
class MHSliderView: UIView {
    var useDigtalFormatFlag: Bool = false //是否使用逗号隔开100，000
    var callBack: MHSliderViewBlock!
    var minUnit: CGFloat = 1 //两个铵钮间的最小间距
    //最小值
    var minNum: CGFloat = 0
    //最大值
    var maxNum: CGFloat = 10
    
    ///左边当前值
    var leftValue: Double = 0 {
        didSet {
            self.callBack?(self.leftValue, self.rightValue)
        }
    }
    
    ///右边当前值
    var rightValue: Double = 0 {
        didSet {
            self.callBack(self.leftValue, self.rightValue)
        }
    }
    
    //左边值label
    private var minTipLab: UITextField!
    //右边值label
    private var maxTipLab: UITextField!
    //线高度
    private var sliderHeight: CGFloat = 3
    
    //左边按钮
    private  var minBtn: UIButton!
    //右边按钮
    private var maxBtn: UIButton!
    //左端线条
    private var minSliderView: UIView!
    //右端线条
    private var maxSliderView: UIView!
    //底部线条
    private var sliderLineView: UIView!
    //按钮大小
    private var btnSize: CGFloat = 38
    
    //记录拖动开始时按钮的相对位置
    private var leftMinCenter: CGFloat = 0
    private var rightMaxCenter: CGFloat = 0
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.leftMinCenter = btnSize/2
        self.rightMaxCenter = btnSize/2
        self.layer.masksToBounds = true
        minTipLab = UITextField.init(frame: CGRect.init(x: 0, y: 0, width: 150, height: 20))
        minTipLab.backgroundColor = UIColor.clear
        minTipLab.textAlignment = .center
        minTipLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        minTipLab.textColor = Theme.mainColor
        self.setLeftTableValue(text: String(format: "%.0f", self.minNum))
        self.minTipLab.layer.borderWidth = 1
        self.minTipLab.layer.borderColor = UIColor.init(hex: 0x939AA8).cgColor
        self.minTipLab.delegate = self
        self.addSubview(minTipLab)
        self.minTipLab.keyboardType = .numberPad
        
        maxTipLab = UITextField.init(frame: CGRect.init(x: 0, y: 0, width: 150, height: 20))
        maxTipLab.backgroundColor = UIColor.clear
        maxTipLab.textAlignment = .center
        maxTipLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        maxTipLab.textColor = Theme.mainColor
        self.setRightTableValue(text: String(format: "%.0f", self.maxNum))
        self.maxTipLab.layer.borderWidth = 1
        self.maxTipLab.layer.borderColor = UIColor.init(hex: 0x939AA8).cgColor
        self.maxTipLab.delegate = self
        self.maxTipLab.keyboardType = .numberPad
        self.addSubview(maxTipLab)
        
        //底部线条
        sliderLineView = UIView.init(frame: CGRect.init(x: self.btnSize/2, y: ((self.frame.size.height - 20) - self.sliderHeight)/2 + 20, width: self.frame.size.width - self.btnSize, height: self.sliderHeight))
        sliderLineView.backgroundColor = Theme.mainColor
        self.addSubview(sliderLineView)
        
        //左侧线条
        minSliderView = UIView.init(frame: CGRect.init(x: sliderLineView.frame.minX, y: sliderLineView.frame.minY, width: 0, height: self.sliderHeight))
        minSliderView.backgroundColor = UIColor.init(hex: 0xBCC8EF, alpha: 1)
        self.addSubview(minSliderView)
        
        //右侧线条
        maxSliderView = UIView.init(frame: CGRect.init(x: 0, y: sliderLineView.frame.minY, width: 0, height: self.sliderHeight))
        maxSliderView.backgroundColor = UIColor.init(hex: 0xBCC8EF, alpha: 1)
        self.addSubview(maxSliderView)
        
        //左侧拖动按钮
        minBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: self.btnSize, height: self.btnSize))
        minBtn.backgroundColor = UIColor.clear
        minBtn.setBackgroundImage(UIImage.init(named: "icon_slider"), for: .normal)
        minBtn.setBackgroundImage(UIImage.init(named: "icon_slider"), for: .highlighted)
        minBtn.center = CGPoint.init(x: self.btnSize/2, y: self.sliderLineView.center.y + 2) //给的图片不是正圆 所以 + 2
        self.addSubview(minBtn)
        
        //左侧按钮手势
        let minPan = UIPanGestureRecognizer.init(target: self, action: #selector(panMinSliderButton(pan:)))
        minBtn.addGestureRecognizer(minPan)
        
        //右侧按钮
        maxBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: self.btnSize, height: self.btnSize))
        maxBtn.backgroundColor = UIColor.clear
        maxBtn.setBackgroundImage(UIImage.init(named: "icon_slider"), for: .normal)
        maxBtn.setBackgroundImage(UIImage.init(named: "icon_slider"), for: .highlighted)
        maxBtn.center = CGPoint.init(x: self.frame.size.width - btnSize/2, y: self.sliderLineView.center.y + 2) //给的图片不是正圆 所以 + 2
        self.addSubview(maxBtn)
        
        //右侧按钮手势
        let maxPan = UIPanGestureRecognizer.init(target: self, action: #selector(panMaxSliderButton(pan:)))
        maxBtn.addGestureRecognizer(maxPan)
        self.addSnpLayout()
        
        self.setOriginParam(leftValue: 0, rightValue: 0)
    }
    
    func addSnpLayout() {
        sliderLineView.snp.makeConstraints { make in
            make.left.equalTo(btnSize/2)
            make.right.equalTo(-btnSize/2)
            make.height.equalTo(self.sliderHeight)
            make.top.equalTo(30 + self.btnSize/2 - self.sliderHeight/2)
        }
        
        minBtn.snp.makeConstraints { make in
            make.centerX.equalTo(self.btnSize/2)
            make.size.equalTo(CGSize.init(width: self.btnSize, height: self.btnSize))
            make.centerY.equalTo(sliderLineView.snp.centerY)
        }
        
        minSliderView.snp.makeConstraints { make in
            make.left.equalTo(sliderLineView.snp.left)
            make.top.equalTo(sliderLineView.snp.top)
            make.height.equalTo(self.sliderHeight)
            make.right.equalTo(minBtn.snp.centerX)
        }
        
        maxBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize.init(width: self.btnSize, height: self.btnSize))
            make.centerY.equalTo(sliderLineView.snp.centerY)
            make.centerX.equalTo(self.sliderLineView.frame.maxX)
        }
        
        maxSliderView.snp.makeConstraints { make in
            make.right.equalTo(sliderLineView.snp.right)
            make.top.equalTo(sliderLineView.snp.top)
            make.height.equalTo(self.sliderHeight)
            make.left.equalTo(maxBtn.snp.centerX)
        }
        
        minTipLab.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.height.equalTo(24)
//            make.centerX.equalTo(minBtn.snp.centerX)
            make.width.equalTo(100)
            make.left.equalTo(18)
        }
        
        maxTipLab.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.height.equalTo(24)
//            make.centerX.equalTo(maxBtn.snp.centerX)
            make.width.equalTo(100)
            make.right.equalTo(-18)
        }
    }
    
    func setLeftTableValue(text: String) {
        if self.useDigtalFormatFlag {
            self.minTipLab.text = XTManageCenter.showPriceInComma(source: text)
        }else{
            self.minTipLab.text = text
        }
    }
    
    func setRightTableValue(text: String) {
        if self.useDigtalFormatFlag {
            self.maxTipLab.text = XTManageCenter.showPriceInComma(source: text)
        }else{
            self.maxTipLab.text = text
        }
    }
    
    
    ///赋值初始化
    func setOriginParam(leftValue: Double, rightValue: Double) {
        if leftValue > self.minNum {
            
        }
       
        //向下取整
       self.setLeftTableValue(text: String(format: "%.0f", floor(leftValue)))
       self.setRightTableValue(text: String(format: "%.0f", floor(rightValue)))
        
        if self.maxNum == self.minNum {
            minBtn.snp.updateConstraints { make in
                make.centerX.equalTo( self.btnSize/2)
            }
            maxBtn.snp.updateConstraints { make in
                make.centerX.equalTo(self.sliderLineView.frame.maxX)
            }
        }else{
            if leftValue > 0 {
                let pre1 = (leftValue - self.minNum) / (self.maxNum - self.minNum)
                let tempPoint1 = self.sliderLineView.frame.size.width * pre1
                minBtn.snp.updateConstraints { make in
                    make.centerX.equalTo(tempPoint1  + self.btnSize/2)
                }
            }else{
                self.setLeftTableValue(text: String(format: "%.0f", self.minNum))
            }
            
            if rightValue > 0 {
                let pre2 = (rightValue - self.minNum) / (self.maxNum - self.minNum)
                let tempPoint2 = self.sliderLineView.frame.size.width * pre2

                maxBtn.snp.updateConstraints { make in
                    make.centerX.equalTo(tempPoint2 + self.btnSize/2)
                }
            }else{
                self.setRightTableValue(text: String(format: "%.0f", self.maxNum))
            }
        }
       
    }
    
    ///参数赋值完后调用resetLayout重新布局
    func resetLayout() {
        if self.minNum > self.maxNum {
            let temp = self.minNum
            self.minNum = self.maxNum
            self.maxNum = temp
        }
//        //两个tipLabel初始位置
//        self.minTipLab.sizeToFit()
//        self.maxTipLab.sizeToFit()
//        let maxTipW = self.maxTipLab.frame.size.width + 10
//        let minTipW = self.maxTipLab.frame.size.width + 10
//        self.maxTipLab.snp.updateConstraints { make in
//            make.width.equalTo(maxTipW)
//        }
//
//        self.minTipLab.snp.updateConstraints { make in
//            make.width.equalTo(minTipW)
//        }
//
//        if minTipW/2 > self.minBtn.center.x {
//            minTipLab.snp.updateConstraints { make in
//                make.centerX.equalTo(minBtn.snp.centerX).offset(minTipW/2 - self.minBtn.center.x)
//            }
//        }
//        if maxTipW/2 > (self.frame.size.width - self.maxBtn.center.x) {
//            maxTipLab.snp.updateConstraints { make in
//                make.centerX.equalTo(self.maxBtn.snp.centerX).offset(-(maxTipW/2 - (self.frame.size.width - self.maxBtn.center.x)))
//            }
//        }
        self.updateConstraints()
    }
    
    ///左侧按钮手势
    @objc func panMinSliderButton(pan: UIPanGestureRecognizer) {
        if self.minNum == self.maxNum {
            return
        }
        let point = pan.translation(in: self)
        if pan.state == .began {
            //手势开始时，拖动按钮的偏移量
            leftMinCenter = (pan.view?.center.x)!
        }
        
        //将总长度分为betNum格
        var betNum = self.maxNum - self.minNum
        if betNum == 0 {
            betNum = 1
        }
        //每格长度是多少
        let unit = self.sliderLineView.frame.size.width/betNum
        let kValue = self.minUnit * unit
        
        //更改按钮当前的位置
        var tempPoint = point.x + leftMinCenter
        if tempPoint > self.sliderLineView.frame.maxX - kValue {
            tempPoint = self.sliderLineView.frame.maxX - kValue
        }
        //最小位置
        if tempPoint < self.sliderLineView.frame.origin.x {
            tempPoint = self.sliderLineView.frame.origin.x
        }
        //右侧按钮是否一起滑动
        if tempPoint > (maxBtn.center.x - kValue) {
            maxBtn.snp.updateConstraints { make in
                make.centerX.equalTo(tempPoint + kValue)
            }
            //右label赋值
            let maxLabelText = ((tempPoint + kValue - self.btnSize/2) / (self.sliderLineView.frame.size.width)) * betNum
            self.setRightTableValue(text: String(format: "%d", Int(floorf(Float(maxLabelText) + Float(self.minNum)))))
        }
        //左按钮更新位置
        minBtn.snp.updateConstraints { make in
            make.centerX.equalTo(tempPoint)
        }
        //左label赋值
        let minLabelText = ((tempPoint - self.btnSize/2) / (self.sliderLineView.frame.size.width)) * betNum
        self.setLeftTableValue(text: String(format: "%d", Int(floorf(Float(minLabelText) + Float(self.minNum)))))
        
        
//        //两个tip label的位置
//        self.minTipLab.sizeToFit()
//        self.maxTipLab.sizeToFit()
//        let maxTipW = self.maxTipLab.frame.size.width + 10
//        let minTipW = self.minTipLab.frame.size.width + 10
//        self.maxTipLab.snp.updateConstraints { make in
//            make.width.equalTo(maxTipW)
//        }

//        self.minTipLab.snp.updateConstraints { make in
//            make.width.equalTo(minTipW)
//        }
//
//        if minTipW/2 > tempPoint {
//            //最左侧
//            minTipLab.snp.updateConstraints { make in
//                make.centerX.equalTo(minBtn.snp.centerX).offset(-minTipW/2 + tempPoint)
//            }
//        }else{
//            if self.maxTipLab.frame.maxX > self.frame.size.width {
//                //处于最右侧
//                let aa = self.frame.size.width - tempPoint
//                self.maxTipLab.snp.updateConstraints { make in
//                    make.centerX.equalTo(self.maxBtn.snp.centerX).offset(-(maxTipW/2 - aa))
//                }
//            }else if (minTipW/2 + tempPoint) > self.maxTipLab.frame.minX  {
//                //两个tipLabel相交时，左侧lable向左偏移
//                let kk = minTipW/2 + maxTipW/2 - (self.maxBtn.center.x - tempPoint)
//                minTipLab.snp.updateConstraints { make in
//                    make.centerX.equalTo(minBtn.snp.centerX).offset(-kk)
//                }
//            }else{
//                minTipLab.snp.updateConstraints { make in
//                    make.centerX.equalTo(minBtn.snp.centerX)
//                }
//            }
//        }
//
        self.leftValue = Double((self.minTipLab.text ?? "0").replacingOccurrences(of: ",", with: "")) ?? 0
        self.rightValue = Double((self.maxTipLab.text ?? "0").replacingOccurrences(of: ",", with: "")) ?? 0
        self.updateConstraints()
        
    }
    
    ///右侧按钮手势
    @objc func panMaxSliderButton(pan: UIPanGestureRecognizer) {
        if self.minNum == self.maxNum {
            return
        }
        let point = pan.translation(in: self)
        if pan.state == .began {
            //手势开始时，拖动按钮的偏移量
            rightMaxCenter = (pan.view?.center.x)!
        }
        //将总长度分为betNum格
        var betNum = self.maxNum - self.minNum
        if betNum == 0 {
            betNum = 1
        }
        //每格长度是多少
        let unit = self.sliderLineView.frame.size.width/betNum
        let kValue = self.minUnit * unit
        
        //更改按钮当前的位置
        var tempPoint = point.x + rightMaxCenter
        if tempPoint > self.sliderLineView.frame.maxX {
            tempPoint = self.sliderLineView.frame.maxX
        }
        if tempPoint < self.sliderLineView.frame.origin.x + kValue {
            tempPoint = self.sliderLineView.frame.origin.x + kValue
        }
        
        if tempPoint < (minBtn.center.x + kValue) {
            minBtn.snp.updateConstraints { make in
                make.centerX.equalTo(tempPoint - kValue)
            }
            //右label赋值
            let minLabelText = ((tempPoint - kValue - self.btnSize/2) / (self.sliderLineView.frame.size.width)) * betNum
            self.setLeftTableValue(text: String(format: "%d", Int(floorf(Float(minLabelText) + Float(self.minNum)))))
        }
        
        maxBtn.snp.updateConstraints { make in
            make.centerX.equalTo(tempPoint)
        }
        
        let maxLabelText = ((tempPoint - self.btnSize/2) / (self.sliderLineView.frame.size.width)) * betNum
        self.setRightTableValue(text: String(format: "%d", Int(floorf(Float(maxLabelText) + Float(self.minNum)))))

//        //两个tip label的位置
//        self.minTipLab.sizeToFit()
//        self.maxTipLab.sizeToFit()
//        let maxTipW = self.maxTipLab.frame.size.width + 10
//        let minTipW = self.maxTipLab.frame.size.width + 10
//        self.maxTipLab.snp.updateConstraints { make in
//            make.width.equalTo(maxTipW)
//        }
//
//        self.minTipLab.snp.updateConstraints { make in
//            make.width.equalTo(minTipW)
//        }
//
//        if maxTipW/2 > (self.frame.size.width - tempPoint) {
//            let pp = (self.frame.size.width - maxTipW/2) - tempPoint
//            maxTipLab.snp.updateConstraints { make in
//                make.centerX.equalTo(maxBtn.snp.centerX).offset(pp)
//            }
//        }else{
//            if maxTipW/2 > (tempPoint - self.minTipLab.frame.maxX)  {
//                //两个tipLabel相交时，右侧lable向右偏移
//                let kk = minTipW/2 + maxTipW/2 - (tempPoint - self.minBtn.center.x)
//                maxTipLab.snp.updateConstraints { make in
//                    make.centerX.equalTo(maxBtn.snp.centerX).offset(kk)
//                }
//            }else{
//                maxTipLab.snp.updateConstraints { make in
//                    make.centerX.equalTo(maxBtn.snp.centerX)
//                }
//            }
//        }
        
        self.leftValue = Double((self.minTipLab.text ?? "0").replacingOccurrences(of: ",", with: "")) ?? 0
        self.rightValue = Double((self.maxTipLab.text ?? "0").replacingOccurrences(of: ",", with: "")) ?? 0
        self.updateConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
}

extension MHSliderView: UITextFieldDelegate{
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField.isEqual(self.minTipLab) {
            var left = Double(textField.text ?? "") ?? 0
            if (self.minNum > left) || (self.maxNum < left){
                left = self.minNum
            }
            self.setOriginParam(leftValue: left, rightValue: self.rightValue)
        }else{
            var right = Double(textField.text ?? "") ?? 0
            if (self.minNum > right) || (self.maxNum < right){
                right = self.maxNum
            }
            self.setOriginParam(leftValue: self.leftValue, rightValue: right)
        }
      
    
    }
    
}
